<?php
    $vmodes = array(
        0 => 'Укажите тип',
        1 => 'Обычное',
        2 => 'Специальное'
    );

    $viewables = array(
        0 => 'Скрыть в Re-ports',
        1 => 'Отображать в Re-ports'
    );

    $isneww = array(
        0 => 'Не помечать',
        1 => 'Пометить как новое'
    );

    $action = Arr::getValue($params, 'id', 0)? ACTIONS::VIEW_UPDATE : ACTIONS::VIEW_NEW;

    $vgroups = Arr::getValue($params, 'vgroups', array());
    $vgroups[0] = array('id'=>0, 'title'=>'Не группировать');

    $cities = Arr::getValue($params, 'cities', array());
    $cities[0] = array('id'=>0, 'city_name'=>'Выберите город');

    $btypes = Arr::getValue($params, 'btypes', array());
    $btypes[0] = array('id'=>0, 'name'=>'Выберите тип');

    $views = Arr::getValue($params, 'views', array());
    $views[0] = array('id'=>0, 'obj_name'=>'Нет', 'obj_type'=>0);

    $types = Arr::getValue($params, 'types', array());

    $params['datatypes'][0] = array('id'=>0,'name'=>'Выберите тип данных');
    //$types[0] = array('id'=>0, 'name'=>'Выберите тип');
?>

<div class="" id="addVwForm-cont">
    <form class="well form-inline margin-horisontal " action="" method="POST" name="addVwForm" id="addVwForm">
        <fieldset >

            <input type="hidden" id="view_action" name="action" value="<?php echo $action;?>">
            <input type="hidden" name="vw_id" value="<?php echo Arr::getValue($params, 'id', 0); ?>">

            <div class="pull-right">
                <div class="control-group" id="cg-view_mode">
                    <label class="control-label" for="view_mode">Тип отображения</label>
                    <div class="controls">
                        <select id="view_type" name="view_mode" class="input-xlarge">
                            <?php
                            $selvalue = Arr::getValue($params, 'view_mode', 0);
                            $all = $vmodes;
                            foreach ($all as $key => $val) {
                                //$key = Arr::getValue($row, 'id', 0);
                                //$val = Arr::getValue($row, 'name', '???');
                                $dis = $key? '' : ' disabled="disabled" style="color:red;" ';
                                $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                echo '<option value="'.$key.'" '.$sel.$dis.'>'.$val.'</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <span class="help-inline"></span>
                </div>
            </div>
            <div class="control-group" id="cg-obj_name">
                <label class="control-label" for="obj_name">Название</label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="obj_name" name="obj_name" value="<?php echo Arr::getValue($params, 'obj_name', ''); ?>">
                </div>
                <span class="help-inline"></span>
            </div>

            <div class="well well-small" id="vwTabs-container">
                <ul class="nav nav-tabs" id="vwTabs" >
                    <li class="active"><a data-toggle="tab" data-target="#vwTabs-table">Навигация</a></li>
                    <li><a data-toggle="tab" data-target="#vwTabs-physical">Физ. параметры</a></li>
                    <li><a data-toggle="tab" data-target="#vwTabs-floors">Срезы данных</a></li>
                </ul>

                <div class="tab-content" id="vwTabs-div">
                    <div class="tab-pane active" id="vwTabs-table">

                        <div class="rightFieldPanel">

                            <div class="control-group" id="cg-dev">
                                <label class="control-label" for="dev">Статус</label>
                                <div class="controls">
                                    <select id="dev" name="dev" class="input-large">
                                        <?php
                                        $selvalue = Arr::getValue($params, 'dev', 0);
                                        $all = VIEWSTATUS::$list;
                                        foreach ($all as $key=>$val) {
                                            //$key = Arr::getValue($row, 'id', 0);
                                            //$val = Arr::getValue($row, 'title', '???');
                                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                            echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <span class="help-inline"></span>
                            </div>

                            <div class="control-group" id="cg-viewable">
                                <label class="control-label" for="viewable">Показывать пользователям Re-ports</label>
                                <div class="controls">
                                    <select id="viewable" name="viewable" class="input-large">
                                        <?php
                                        $selvalue = Arr::getValue($params, 'viewable', 1);
                                        $all = $viewables;
                                        foreach ($all as $key => $val) {
                                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                            echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <span class="help-inline"></span>
                            </div>

                            <div class="control-group" id="cg-is_new">
                                <label class="control-label" for="is_new">Пометить меткой "New"</label>
                                <div class="controls">
                                    <select id="is_new" name="is_new" class="input-large">
                                        <?php
                                        $selvalue = Arr::getValue($params, 'is_new', 0);
                                        $all = $isneww;
                                        foreach ($all as $key => $val) {
                                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                            echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <span class="help-inline"></span>
                            </div>



                            <p>&nbsp;</p>
                            <p>&nbsp;</p>
                            <p>&nbsp;</p>
                            <p>&nbsp;</p>



                        </div>

                        <div class="control-group" id="cg-conception">
                            <label class="control-label" for="conception">Концепция</label>
                            <div class="controls">
                                <select id="conception" name="conception" class="input-large">
                                    <?php
                                    echo conceptionSelectorOptions(Arr::getValue($params, 'conception', ''));
                                    ?>
                                </select>

                                <button type="button" class="btn btn-success" id="addVwCnc-open"><i class="icon-plus icon-white"></i> Добавить </button>
                            </div>
                            <span class="help-inline"></span>
                        </div>


                        <div class="control-group" id="cg-city_id">
                            <label class="control-label" for="city_id">Город</label>
                            <div class="controls">
                                <select id="city_id" name="city_id" class="input-large">
                                    <?php
                                    $selvalue = Arr::getValue($params, 'city_id', 0);
                                    $all = $cities;
                                    foreach ($all as $row) {
                                        $key = Arr::getValue($row, 'id', 0);
                                        $val = Arr::getValue($row, 'city_name', '???');
                                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                        $dis = $key? '' : ' disabled="disabled" style="color:red;" ';
                                        echo '<option value="'.$key.'" '.$sel.$dis.'>'.$val.'</option>';
                                    }
                                    ?>
                                </select>

                                <button type="button" class="btn btn-success" id="addVwCity-open"><i class="icon-plus icon-white"></i> Добавить </button>
                            </div>
                            <span class="help-inline"></span>
                        </div>


                        <h4>В таблице</h4>
                        <hr style="margin: 3px 3px 10px;">

                        <div class="control-group" id="cg-group">
                            <label class="control-label" for="group">Группа</label>
                            <div class="controls">
                                <select id="group" name="group" class="input-large">
                                    <?php
                                    $selvalue = Arr::getValue($params, 'group', 0);
                                    $all = $vgroups;
                                    foreach ($all as $row) {
                                        $key = Arr::getValue($row, 'id', 0);
                                        $val = Arr::getValue($row, 'title', '???');
                                        $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                        echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                                    }
                                    ?>
                                </select>

                                <button type="button" class="btn btn-success" id="addVwGroup-open"><i class="icon-plus icon-white"></i> Добавить </button>
                            </div>
                            <span class="help-inline"></span>
                        </div>

                        <div class="control-group" id="cg-obj_short_name">
                            <label class="control-label" for="obj_short_name">Краткое название в группе</label>
                            <div class="controls">
                                <input type="text" class="input-large" id="obj_short_name" name="obj_short_name" value="<?php echo Arr::getValue($params, 'obj_short_name', ''); ?>">
                            </div>
                            <span class="help-inline"></span>
                        </div>

                    </div>



                    <div class="tab-pane" id="vwTabs-physical">

                        <div class="rightFieldPanel">

                            <div class="control-group">
                                <label class="control-label" for="obj_type">Тип объекта</label>
                                <div class="controls">
                                    <select id="obj_type" name="obj_type" class="input-large">

                                        <?php
                                        $selvalue = Arr::getValue($params, 'obj_type', 0);
                                        $obj_types = $types;
                                        foreach ($obj_types as $key=>$val) {
                                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                            $t = $key? ' ('.Arr::getValue($val, 'datatypename', '---').', '.Arr::getValue($val, 'unit', '').')' : '';
                                            echo '<option value="'.$key.'" '.$sel.'>'.$val['name'].$t.'</option>';
                                        }
                                        ?>
                                    </select>
                                    <button type="button" class="btn btn-success" id="addOT-open"><i class="icon-plus icon-white"></i> Добавить </button>
                                    <span class="help-inline"></span>
                                </div>
                            </div>

                            <div class="control-group" id="cg-build_type">
                                <label class="control-label" for="build_type">Тип помещения</label>
                                <div class="controls">
                                    <select id="build_type" name="build_type" class="input-large">
                                        <?php
                                        $selvalue = Arr::getValue($params, 'build_type', 0);
                                        $all = $btypes;
                                        foreach ($all as $row) {
                                            $key = Arr::getValue($row, 'id', 0);
                                            $val = Arr::getValue($row, 'name', '???');
                                            $dis = $key? '' : ' disabled="disabled" style="color:red;" ';
                                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                            echo '<option value="'.$key.'" '.$sel.$dis.'>'.$val.'</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <span class="help-inline"></span>
                            </div>

                            <div class="control-group" id="cg-parent_id">
                                <label class="control-label" for="parent_id">Находится в</label>
                                <div class="controls">
                                    <select id="parent_id" name="parent_id" class="input-large">
                                        <?php
                                        $selvalue = Arr::getValue($params, 'parent_id', 0);
                                        $all = $views;
                                        foreach ($all as $row) {
                                            $key = Arr::getValue($row, 'id', 0);
                                            $val = Arr::getValue($row, 'obj_name', '???');

                                            if ($key>0 && (Arr::getValue($row, 'obj_type', 100000)>1))  continue;
                                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                                            echo '<option value="'.$key.'" '.$sel.'>'.$val.'</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                <span class="help-inline"></span>
                            </div>



                            <p>&nbsp;</p>
                            <p>&nbsp;</p>
                            <p>&nbsp;</p>
                            <p>&nbsp;</p>
                        </div>

                        <div class="control-group" id="cg-address">
                            <label class="control-label" for="address">Адрес</label>
                            <div class="controls">
                                <textarea class="input-large" id="address" name="address" rows="2"><?php echo Arr::getValue($params, 'address', ''); ?></textarea>
                            </div>
                            <span class="help-inline"></span>
                        </div>

                        <div class="control-group" id="cg-coords">
                            <span class="pull-left">Координаты</span>

                            <div class="pull-left" style="margin: 0 0 0 15px">
                                <label class="control-label" for="lattitude">Широта (lat)</label>
                                <div class="controls">
                                    <input type="text" class="input-small" id="lattitude" name="lattitude" value="<?php echo Arr::getValue($params, 'lattitude', ''); ?>">
                                </div>
                                <span class="help-inline"></span>
                            </div>

                            <div class="pull-left" style="margin: 0 0 0 5px">
                                <label class="control-label" for="longitude">Долгота (lon)</label>
                                <div class="controls">
                                    <input type="text" class="input-small" id="longitude" name="longitude" value="<?php echo Arr::getValue($params, 'longitude', ''); ?>">
                                </div>
                                <span class="help-inline"></span>
                            </div>

                            <div style="clear:left;"></div>

                        </div>

                        <div class="control-group" id="cg-area">
                            <label class="control-label" for="area">Площадь</label>
                            <div class="controls">
                                <input type="text" class="input-large" id="area" name="area" value="<?php echo Arr::getValue($params, 'area', ''); ?>"> <span> кв.м.</span>
                            </div>
                            <span class="help-inline"></span>
                        </div>

                    </div>


                    <div class="tab-pane" id="vwTabs-floors">

                    </div>

                </div>
            </div>

            <div class="form-actions ">
                <div class="pull-right">
                    <button type="submit" class="btn btn-primary" id="vw-submit" data-loading-text="Сохранение.." data-complete-text="Сохранено" autocomplete="off">
                        <i class="icon-ok icon-white"></i>
                        <span>Сохранить</span>
                    </button>
                    <button type="reset" class="btn btn-danger" id="vw-cancel"><i class="icon-remove icon-white"></i> Закрыть</button>
                </div>
            </div>
        </fieldset>
    </form>
</div>


<?php



?>


<script>


function addVwFormRefresh() {

    var vtype = $('#view_type').val();
    if (vtype*1 == 1) $('#vwTabs-container').show();
    else $('#vwTabs-container').hide();


    var gr = $('#group').val();
    if (gr*1>0) $('#obj_short_name').removeAttr('disabled');
    else $('#obj_short_name').attr('disabled','disabled');

    var gr = $('#build_type').val();
    if (gr*1 != 1) $('#parent_id').removeAttr('disabled');
    else $('#parent_id').attr('disabled','disabled');

};

function vwWrongFields(wf) {
    wf = wf || {};
    var wf_count = 0;

    var cgdivs = Elm.addVwForm.find('div.error').removeClass('error');
    cgdivs.find('span.help-inline').empty();

    for(var id in wf) {
        if (!wf.hasOwnProperty(id)) continue;
        var msg = wf[id];

        var cg = $('#cg-'+id).addClass('error');
        cg.find('span.help-inline').html(msg);
        wf_count++;
    }

    debug();

    var lis = $('#vwTabs > li').removeClass('error');
    var divs = $('#vwTabs-div > div.tab-pane');

    divs.each(function() {
        var $this = $(this);
        if ($this.find('div.error').length>0) {
            var id = $this.attr('id');
            lis.each(function() {
                if ($(this).find('a').attr('data-target') == ('#'+id)) {
                    $(this).addClass('error');
                    return false;
                }
            });
        }
    });

    return wf_count;
}



function submitVwForm() {
    vwWrongFields({});
    var send = Elm.addVwForm.serialize();
    progressButton();

    jsonRequest(
        'views.php?View',
        send,

        function(data) {
            vwWrongFields({});

            if(checkSession(data)) {
                if (!data.state) {
                    uiAlert(data.message,'Error');
                    resetButton();
                    return;
                }

                if (data.hasOwnProperty('response_data') && data.response_data) {
                    var resp = data.response_data;
                    if (resp.hasOwnProperty('wrongFields')) {
                        var wf = vwWrongFields(resp.wrongFields);

                        if (wf*1>0) {
                            errorButton();
                            return;
                        }
                    }

                    if (resp.hasOwnProperty('insertedId')) {
                        if (
                            Elm.addVwForm.hasOwnProperty('successCallback')
                            && (typeof(Elm.addVwForm.successCallback) == 'function')
                        ) {
                            $('#view_action').val('<?php echo ACTIONS::VIEW_UPDATE; ?>');
                            var cdata;
                            if (data.hasOwnProperty('request_data') && data.request_data) cdata = data.request_data;
                            else cdata = {};
                            $.extend(cdata, resp);
                            var cb = Elm.addVwForm.successCallback;
                            Elm.addVwForm.successCallback = function() {};
                            cb(cdata);
                        }
                        completeButton();
                        return;
                    }
                }
                //closeVwDialog();
            }
            else Elm.loginFormModal.dialog('open');
            resetButton();
        },

        function() {
            vwWrongFields({});
            resetButton();
            uiAlert('Ошибка соединения','Error');
        }
    );
    return;
}

function progressButton() {
    Elm.vwSubmitBtnText.html('Сохранение..');
    Elm.vwSubmitBtn.attr('disabled', 'disabled');
}

function completeButton() {
    Elm.vwSubmitBtnText.html('Сохранено.');
}

function errorButton() {
    Elm.vwSubmitBtnText.html('Исправьте данные');
}

function resetButton() {
    Elm.vwSubmitBtn.removeAttr('disabled');
    Elm.vwSubmitBtnText.html('Сохранить');
}




    $(function() {



        //Elm.addCntFormCont = $('#addCntForm-cont');
        Elm.addVwForm = $('#addVwForm');

        Elm.vwCancelBtn = $('#vw-cancel');
        Elm.vwSubmitBtn = $('#vw-submit');
        Elm.vwSubmitBtnText = $('#vw-submit > span');
        /*Elm.vwFloorsTab = $('#vwFloors');

        Elm.vwFloorsTab.find('a[data-toggle="tab"]').on('show', function (e) {
            console.log(e.target); // Активная вкладка
            console.log(e.relatedTarget); // Предыдущая активная вкладка

            if ($(e.target).attr('data-target') == 'vwFloors-plus') {
                alert('plus');
                return false;
            }
        });
*/

        //Elm.vwSubmitBtn.button();

        $('#addOT-open').click(function() {
            addOTDialogOpen(function(data) {
                $('#obj_type').append(
                    $('<option>').attr({value:data.id}).html($('#ot_name').val()+' ('+data.datatype+')')
                ).val(data.id);
            });
        });

        if (Elm.hasOwnProperty('addVwGroup')) {

            Elm.addVwGroupForm.successCallback = function(cdata) {
                $('#group').append(
                    $('<option>').attr({value:cdata.insertedId}).html(cdata.vwg_title)
                ).val(cdata.insertedId);
                addVwFormRefresh();
            };

            $('#addVwGroup-open').click(function() {
                Elm.addVwGroup.dialog('open');
            });
        }

        if (Elm.hasOwnProperty('addCity')) {
            Elm.addCityForm.successCallback = function(cdata) {
                $('#city_id').append(
                    $('<option>').attr({value:cdata.insertedId}).html(cdata.f_city_name)
                ).val(cdata.insertedId);
                addVwFormRefresh();
            };

            $('#addVwCity-open').click(function() {
                Elm.addCity.dialog('open');
            });
        }

        if (Elm.hasOwnProperty('addCnc')) {
            Elm.addCncForm.successCallback = function(cdata) {
                var newopt = $('<option id="opt_cnc'+cdata.insertedId+'">').attr({value:cdata.insertedId}).html(cdata.cnc_name);
                if (cdata.cnc_parent_id*1>0) {
                    var gr = $('#og_cnc_'+cdata.cnc_parent_id);
                    if (!gr.length) {
                        var oldopt = $('#opt_cnc_'+cdata.cnc_parent_id);
                        if (!oldopt.length) {
                            addVwFormRefresh();
                            return;
                        }
                        var oname = oldopt.html();
                        oldopt.remove();
                        gr = $('<optgroup id="og_cnc_'+cdata.cnc_parent_id+'">').attr({value:cdata.cnc_parent_id, label:oname}).appendTo('#conception');
                    }
                    gr.append(newopt);
                    $('#conception').val(cdata.insertedId);
                }
                else {
                    $('#conception').append(newopt).val(cdata.insertedId);
                }
                addVwFormRefresh();
            };

            $('#addVwCnc-open').click(function() {
                Elm.addCnc.dialog('open');
            });
        }

        Elm.vwSubmitBtn.click(function(e) {
            e.preventDefault();
            submitVwForm();
            //if ((Elm.addVwForm.hasOwnProperty('successCallback')) && typeof(Elm.addVwForm.successCallback) == 'function') Elm.addVwForm.successCallback();
            return false;
        });


        Elm.vwCancelBtn.click(function() {
            closeVwDialog();
            resetButton();
        });



        addVwFormRefresh();
        Elm.addVwForm.change(function(){
            addVwFormRefresh();
            resetButton();
        });

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////


        //var t = (new TabsObject('#vwTabs-floors')).init().addTab('default', 'New tab', 'text');

        window.VwFloor = new Floors('#vwTabs-floors');
        VwFloor.vwId = <?php echo Arr::getValue($params, 'id', ' 0 '); ?>;
        /*f.actions = {
            refreshAction = '<?php echo ACTIONS::VIEW_FLOORS_GET; ?>',

        }*/
        VwFloor.init();


    });
</script>